// Vue应用实例
new Vue({
    el: '#app',
    data: {
        qualityMetrics: null,
        priceTrends: [],
        productStats: [],
        placeAnalysis: [],
        priceDistribution: [],
        charts: {},
        loading: false,
        error: null
    },
    mounted() {
        this.initCharts();
        this.fetchData();
        // 每5分钟刷新一次数据
        setInterval(() => {
            this.fetchData();
        }, 300000);
    },
    methods: {
        initCharts() {
            // 初始化所有图表
            this.charts.priceTrend = echarts.init(document.getElementById('price-trend-chart'));
            this.charts.productStats = echarts.init(document.getElementById('product-stats-chart'));
            this.charts.placeAnalysis = echarts.init(document.getElementById('place-analysis-chart'));
            this.charts.priceDistribution = echarts.init(document.getElementById('price-distribution-chart'));

            // 监听窗口大小变化
            window.addEventListener('resize', () => {
                Object.values(this.charts).forEach(chart => {
                    if (chart && typeof chart.resize === 'function') {
                        chart.resize();
                    }
                });
            });
        },
        
        async fetchData() {
            this.loading = true;
            this.error = null;
            
            try {
                // 获取数据质量指标
                await this.fetchQualityMetrics();
                
                // 获取价格趋势数据
                await this.fetchPriceTrends();
                
                // 获取产品统计数据
                await this.fetchProductStats();
                
                // 获取产地分析数据
                await this.fetchPlaceAnalysis();
                
                // 获取价格分布数据
                await this.fetchPriceDistribution();
                
            } catch (error) {
                console.error('数据获取失败:', error);
                this.error = '数据获取失败，请稍后重试';
            } finally {
                this.loading = false;
            }
        },
        
        async fetchQualityMetrics() {
            try {
                const response = await axios.get('/api/quality-metrics');
                if (response.data.status === 'success') {
                    const metrics = response.data.data;
                    this.qualityMetrics = metrics;
                    
                    // 更新DOM元素
                    const totalRecordsEl = document.getElementById('total-records');
                    const uniqueProductsEl = document.getElementById('unique-products');
                    const uniquePlacesEl = document.getElementById('unique-places');
                    const avgQualityEl = document.getElementById('avg-quality');
                    
                    if (totalRecordsEl) totalRecordsEl.textContent = metrics.total_records || 0;
                    if (uniqueProductsEl) uniqueProductsEl.textContent = metrics.unique_products || 0;
                    if (uniquePlacesEl) uniquePlacesEl.textContent = metrics.unique_places || 0;
                    if (avgQualityEl) avgQualityEl.textContent = metrics.avg_quality ? metrics.avg_quality.toFixed(1) : '0.0';
                }
            } catch (error) {
                console.error('获取质量指标失败:', error);
            }
        },
        
        async fetchPriceTrends() {
            try {
                const response = await axios.get('/api/price-trends');
                if (response.data.status === 'success') {
                    this.priceTrends = response.data.data;
                    this.updatePriceTrendChart(response.data.data);
                }
            } catch (error) {
                console.error('获取价格趋势失败:', error);
            }
        },
        
        async fetchProductStats() {
            try {
                const response = await axios.get('/api/product-stats');
                if (response.data.status === 'success') {
                    this.productStats = response.data.data;
                    this.updateProductStatsChart(response.data.data);
                }
            } catch (error) {
                console.error('获取产品统计失败:', error);
            }
        },
        
        async fetchPlaceAnalysis() {
            try {
                const response = await axios.get('/api/place-analysis');
                if (response.data.status === 'success') {
                    this.placeAnalysis = response.data.data;
                    this.updatePlaceAnalysisChart(response.data.data);
                }
            } catch (error) {
                console.error('获取产地分析失败:', error);
            }
        },
        
        async fetchPriceDistribution() {
            try {
                const response = await axios.get('/api/price-distribution');
                if (response.data.status === 'success') {
                    this.priceDistribution = response.data.data;
                    this.updatePriceDistributionChart(response.data.data);
                }
            } catch (error) {
                console.error('获取价格分布失败:', error);
            }
        },
        
        updatePriceTrendChart(data) {
            if (!data || data.length === 0) {
                console.warn('价格趋势数据为空');
                return;
            }
            
            try {
                const dates = [...new Set(data.map(item => item.pub_date))].sort();
                const products = [...new Set(data.map(item => item.product_name))].slice(0, 10); // 限制显示产品数量
                
                const series = products.map(product => ({
                    name: product,
                    type: 'line',
                    smooth: true,
                    data: dates.map(date => {
                        const item = data.find(d => d.pub_date === date && d.product_name === product);
                        return item ? parseFloat(item.avg_price) : null;
                    })
                }));

                const option = {
                    title: {
                        text: '价格趋势分析',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(params) {
                            let result = params[0].axisValue + '<br/>';
                            params.forEach(param => {
                                if (param.value !== null) {
                                    result += param.marker + param.seriesName + ': ¥' + param.value.toFixed(2) + '<br/>';
                                }
                            });
                            return result;
                        }
                    },
                    legend: {
                        data: products,
                        type: 'scroll',
                        bottom: 0,
                        pageButtonItemGap: 5,
                        pageButtonGap: 20,
                        pageIconSize: 10
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '15%',
                        top: '15%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: dates,
                        axisLabel: {
                            rotate: 45
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '价格(元)',
                        axisLabel: {
                            formatter: '¥{value}'
                        }
                    },
                    series: series
                };

                this.charts.priceTrend.setOption(option, true);
            } catch (error) {
                console.error('更新价格趋势图表失败:', error);
            }
        },
        
        updateProductStatsChart(data) {
            if (!data || data.length === 0) {
                console.warn('产品统计数据为空');
                return;
            }
            
            try {
                const option = {
                    title: {
                        text: '产品价格统计',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        },
                        formatter: function(params) {
                            let result = params[0].axisValue + '<br/>';
                            params.forEach(param => {
                                result += param.marker + param.seriesName + ': ¥' + param.value.toFixed(2) + '<br/>';
                            });
                            return result;
                        }
                    },
                    legend: {
                        data: ['平均价格', '最低价格', '最高价格'],
                        bottom: 0
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '15%',
                        top: '15%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'value',
                        name: '价格(元)',
                        axisLabel: {
                            formatter: '¥{value}'
                        }
                    },
                    yAxis: {
                        type: 'category',
                        data: data.map(item => item.product_name),
                        axisLabel: {
                            interval: 0,
                            formatter: function(value) {
                                return value.length > 8 ? value.substring(0, 8) + '...' : value;
                            }
                        }
                    },
                    series: [
                        {
                            name: '平均价格',
                            type: 'bar',
                            data: data.map(item => parseFloat(item.avg_price)),
                            itemStyle: {
                                color: '#5470c6'
                            }
                        },
                        {
                            name: '最低价格',
                            type: 'bar',
                            data: data.map(item => parseFloat(item.min_price)),
                            itemStyle: {
                                color: '#91cc75'
                            }
                        },
                        {
                            name: '最高价格',
                            type: 'bar',
                            data: data.map(item => parseFloat(item.max_price)),
                            itemStyle: {
                                color: '#fac858'
                            }
                        }
                    ]
                };

                this.charts.productStats.setOption(option, true);
            } catch (error) {
                console.error('更新产品统计图表失败:', error);
            }
        },
        
        updatePlaceAnalysisChart(data) {
            if (!data || data.length === 0) {
                console.warn('产地分析数据为空');
                return;
            }
            
            try {
                const option = {
                    title: {
                        text: '产地分析',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        data: data.map(item => item.place),
                        type: 'scroll',
                        pageButtonItemGap: 5
                    },
                    series: [
                        {
                            name: '产地分布',
                            type: 'pie',
                            radius: ['30%', '70%'],
                            center: ['60%', '50%'],
                            data: data.map(item => ({
                                name: item.place,
                                value: parseInt(item.record_count)
                            })),
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            },
                            label: {
                                formatter: '{b}\n{d}%'
                            }
                        }
                    ]
                };

                this.charts.placeAnalysis.setOption(option, true);
            } catch (error) {
                console.error('更新产地分析图表失败:', error);
            }
        },
        
        updatePriceDistributionChart(data) {
            if (!data || data.length === 0) {
                console.warn('价格分布数据为空');
                return;
            }
            
            try {
                const option = {
                    title: {
                        text: '价格分布分析',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        },
                        formatter: function(params) {
                            let result = params[0].axisValue + '<br/>';
                            params.forEach(param => {
                                if (param.value !== null && param.value !== undefined) {
                                    result += param.marker + param.seriesName + ': ¥' + param.value.toFixed(2) + '<br/>';
                                }
                            });
                            return result;
                        }
                    },
                    legend: {
                        data: ['25%分位数', '中位数', '75%分位数', '平均值'],
                        bottom: 0
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '15%',
                        top: '15%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'value',
                        name: '价格(元)',
                        axisLabel: {
                            formatter: '¥{value}'
                        }
                    },
                    yAxis: {
                        type: 'category',
                        data: data.map(item => item.product_name),
                        axisLabel: {
                            interval: 0,
                            formatter: function(value) {
                                return value.length > 8 ? value.substring(0, 8) + '...' : value;
                            }
                        }
                    },
                    series: [
                        {
                            name: '25%分位数',
                            type: 'bar',
                            data: data.map(item => item.price_quartiles ? parseFloat(item.price_quartiles[0]) : 0),
                            itemStyle: {
                                color: '#73c0de'
                            }
                        },
                        {
                            name: '中位数',
                            type: 'bar',
                            data: data.map(item => item.price_quartiles ? parseFloat(item.price_quartiles[1]) : 0),
                            itemStyle: {
                                color: '#5470c6'
                            }
                        },
                        {
                            name: '75%分位数',
                            type: 'bar',
                            data: data.map(item => item.price_quartiles ? parseFloat(item.price_quartiles[2]) : 0),
                            itemStyle: {
                                color: '#fc8452'
                            }
                        },
                        {
                            name: '平均值',
                            type: 'line',
                            data: data.map(item => parseFloat(item.mean_price)),
                            itemStyle: {
                                color: '#ee6666'
                            },
                            lineStyle: {
                                width: 3
                            }
                        }
                    ]
                };

                this.charts.priceDistribution.setOption(option, true);
            } catch (error) {
                console.error('更新价格分布图表失败:', error);
            }
        }
    }
});